<?php
namespace library\Core;
use library\Core\Exception\System;

class ConfigLoader {

    private static $_instance = null;
    private static $_configList = array();
    private static $_basePathList = array();

    private function __construct() {
        
    }

    public static function getInstance() {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    public static function setBasePath($path) {
        if (false === in_array($path, self::$_basePathList)) {
            self::$_basePathList[] = $path;
        }
    }

    /**
     * 加载配置文件
     *
     * @param string $file 待加载文件名
     * @param string $path 文件路径
     *
     * @return mixed
     * @throws OrderSdk_Exception_ResourceException
     */
    public static function loadConfig($file, $path = null) {

        if (false === isset(self::$_configList[$file])) {
            $filePath = array();

            if (empty($path)) {
                foreach (self::$_basePathList as $basePath) {
                    $filePath[] = $basePath . DIRECTORY_SEPARATOR . $file;
                }
            } else {
                $filePath[] = $path . DIRECTORY_SEPARATOR . $file;
            }

            $exist = false;
            foreach ($filePath as $file) {
                if (is_file($file)) {
                    self::$_configList[$file] = include $file;
                    $exist = true;
                    break;
                }
            }
            if (!$exist) {
                throw new System('config file not exists', 130);
            }
        }

        return self::$_configList[$file];
    }

}
